package com.sugar.controller;


import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.beans.PropertyEditorSupport;
import com.sugar.entity.User;

@RestController
@RequestMapping("/api/user")
public class UserController {

    /**
     * 使用 @InitBinder 自定义数据绑定
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 自定义一个属性编辑器，将所有传入的名称去除前后空格
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(text == null ? null : text.trim());
            }
        });

        // 忽略未绑定字段
        binder.setDisallowedFields("age");
    }

    /**
     * 接收并打印用户数据
     */
    @PostMapping("/create")
    public String createUser(@ModelAttribute User user) {
        return "Received user: " + user.getName() + ", age: " + user.getAge();
    }
}
